# -*- coding: utf-8 -*-¨

import helpers.dbmanager
import types

import models.books

class NotesModel():
    db = None
    booksModel = None
    defaultBookId = "0AqSWlRWYPabFdHZ4aXVmdWZtd2QzSFBfSjhZUmZFZUE"

    def __init__(self, booksModel):
        self.booksModel = booksModel

    def getNotesByBookId(self, bookId):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        tmpNotes = self.db.getNotesByBookID(bookId)
        notes = {}
        for note in tmpNotes:
            for name, value in note.iteritems():
                if isinstance(value, types.NoneType) : note[name] = ""

            note["bookId"] = bookId
            notes[note["id"]] = note

        return notes

    def saveNote(self, note):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        if "header" not in note or len(note["header"]) == 0:
            return False
        if "bookId" not in note or self.booksModel.getBookExists(note["bookId"]) is False:
            return False
        if "id" in note and len(note["id"]) > 0:
            self.db.updateNote(note["bookId"], note["id"], note["header"], note["body"], note["tags"])
        else:
            note["id"] = self.db.createNote(note["bookId"], note["header"], note["body"], note["tags"])

        return note["id"]

    def deleteNote(self, bookId, noteId):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        return self.db.deleteNote(bookId, noteId)

    def getBookNoteById(self, bookId, noteId):
        notes = self.getNotesByBookId(bookId)
        return notes.get(noteId, None)

    def getBookNotesByIds(self, bookId, ids):
        notes = self.getNotesByBookId(bookId)
        ret = {}
        for id in ids:
            if id in notes:
                ret[id] = notes[id]
        return ret

    def getDefaultBookId(self):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        books = self.db.listBooks(u"- nezařazené -")
        if len(books) is 0:
            return None
        return books[0]["id"]

    def getNewestNotes(self, offset, limit, bookId = None):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        notes = self.db.getNewestNotes(bookId)
        validNotes = notes[offset:(offset+limit)]
        for note in validNotes:
            note["bookName"] = self.booksModel.getBookName(note["book_id"]);
            for key, val in note.iteritems():
                if val is None:
                    note[key] = ""
        
        return validNotes;

    def getNewestNotesCount(self, bookId = None):
        self.db = helpers.dbmanager.DBManager.getInstance().get()
        return len(self.db.getNewestNotes(bookId))